package com.gocoolmall.auth.Controller;

import com.alibaba.fastjson.TypeReference;
import com.gocoolmall.auth.feign.MemberFeignService;
import com.gocoolmall.auth.feign.ThirdFeignService;
import com.gocoolmall.auth.vo.UserLoginVo;
import com.gocoolmall.auth.vo.UserRegistVo;
import com.gocoolmall.common.constant.AuthServerConstant;
import com.gocoolmall.common.exception.BizCodeEnume;
import com.gocoolmall.common.utils.R;
import com.gocoolmall.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    /**
     * 发送一个请求直接跳转到一个页面
     * SpringMvc viewController;将一个请求页面映射过来。
     * @return
     */
//    @GetMapping("/login.html")
//    public String LoginPage(){
//
//        return "login";
//    }
//    @GetMapping("/reg.html")
//    public String regPage(){
//        return "reg";
//    }

    @Autowired
    ThirdFeignService thirdFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        //1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long time = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - time < 60000){
                System.out.println("频繁登录请60秒后再试：");
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.PRODUCT_UP_EXCEPTION.getMsg());
            }
            System.out.println("验证码是从redis获取");
        }else {
            //2、验证码的在次校验。redis. 存在key-phone,value-code  sms:code:    ->
            String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
            System.out.println("redis没有生成验证码："+code);
            //redis缓存验证码，防止同一个phone在60秒内再次发送验证码
            redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,code, 10,TimeUnit.MINUTES);
            redisCode=code;
        }
        String codeReq = redisCode.split("_")[0];
        System.out.println("上传验证码："+codeReq);

        thirdFeignService.snedCode(phone, codeReq);
        return R.ok();
    }

    /**
     * edirectAttributes redirectAttributes:模拟重定向携带数据
     * TODO 重定向携带数据，利用session原理。将数据放在session中。
     * //TODO 1、分布式下的session问题
     *
     * 只要跳到下一个页面取出这个数据以后，session里面的数据就会删掉
     * chong'dong
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result,
//                         Model model
                         RedirectAttributes redirectAttributes,
                         HttpSession session
                        ){
        //前置校验
        if (result.hasErrors()){
//            Map<String,String> error = new HashMap<>();
//            result.getFieldErrors().stream().map(fieldError ->{
////                String field = fieldError.getField();
////                String defaultMessage = fieldError.getDefaultMessage();
////                String put = error.put(field, defaultMessage);
//                return put;
//            })
            Map<String, String> errors = null;
            try {
                errors = result.getFieldErrors().stream().
                        collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(errors);
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            //Request method 'POST' not supported
            //用户注册/-regist[post]  ->>>转发/reg.html(路径映射默认是get方式访问的。)

            //校验出错，转发到注册页
//            return "forward:/reg.html";  //转发=forward
//            return "reg";  //转发=forward
            return "redirect:http://auth.gocoolmall.com/reg.html";
        }
        //正真的注册，调用远程服务进行注册
        //1、校验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        System.out.println("redis的验证码："+redisCode.split("_")[0]);
        if (!StringUtils.isEmpty(redisCode)){
            //验证码通过。//真正注册。调用远程服务进行注册
            if(code.equals(redisCode.split("_")[0])){
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证通过，//调用远程服务进行注册。
                R regist = memberFeignService.regist(vo);
                if (regist.getCode() == 0){
                    //成功
                    System.out.println("注册成功");
                    return "redirect:http://auth.gocoolmall.com/login.html";
                }else {
                    //失败
                    System.out.println("注册失败");
                    HashMap<String, String> errors = new HashMap<>();
                    errors.put("msg", regist.getDate("msg", new TypeReference<String>(){}));
                    errors.put("msg", regist.getDate(new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gocoolmall.com/reg.html";
                }
            }
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.gocoolmall.com/reg.html";
        }
        //注册成功返回到首页，回到登录页
        return "redirect:http://auth.gocoolmall.com/login.html";
    }

    //
    @PostMapping("/login")
    public String loging(UserLoginVo vo , RedirectAttributes redirectAttributes,
                         HttpSession session){
        //远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0){
            //成功
            MemberRespVo date = login.getDate("date", new TypeReference<MemberRespVo>() {});
            System.out.println("远程登录成功"+date);
            //成功登录放到session中
            session.setAttribute(AuthServerConstant.LOGIN_USER, date);
            return "redirect:http://gocoolmall.com/";
        }else {
            //失败
            HashMap<String, String> errors = new HashMap<>();
            errors.put("msg", login.getDate("msg", new TypeReference<String>(){}));
//            errors.put("msg", login.getDate(new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            System.out.println("远程登录失败:"+errors.get("msg"));
            return "redirect:http://auth.gocoolmall.com/login.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null){
            //没有登录
            return "login";
        }else {
            return "redirect:http://gocoolmall.com";
        }
    }
}
